package com.chinawlx.wlxteacher.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chinawlx.wlxteacher.R;
import com.chinawlx.wlxteacher.ui.activity.WLXCourseRollCallActivity;
import com.chinawlx.wlxteacher.utils.ConvertUtils;
import com.chinawlx.wlxteacher.utils.WLXDateUtil;
import com.chinawlx.wlxteacher.utils.WLXGreenDaoUtil;
import com.chinawlx.wlxteacher.utils.WLXLogUtil;
import com.chinawlx.wlxteacher.utils.WLXTeacherConstant;
import com.chinawlx.wlxteacher.wlx_schedule;
import com.chinawlx.wlxteacher.wlx_student_order_detail;
import com.chinawlx.wlxteacher.wlx_student_order_detailDao;
import com.chinawlx.wlxteacher.wlx_student_study;
import com.chinawlx.wlxteacher.wlx_student_studyDao;

import java.util.ArrayList;
import java.util.List;


/**
 * 课程管理适配器
 * Created by wlx on 16/10/20.
 */

public class CourseManageAdapter extends BaseAdapter {
    private Context mContext;
    private String grade_id;
//    private ArrayList<String> studyCodes;
    private List<wlx_schedule> scheduleList=new ArrayList<>();
    private long currentTimestamp = System.currentTimeMillis() / 1000L; //当前时间的时间戳
    public CourseManageAdapter(Context mContext,String grade_id){
        this.mContext=mContext;
        this.grade_id=grade_id;
    }

    public void setData(List<wlx_schedule> scheduleList){
        this.scheduleList.clear();
        this.scheduleList.addAll(scheduleList);

    }
    public void addData(List<wlx_schedule> scheduleList){
        this.scheduleList.addAll(scheduleList);

    }
    @Override
    public int getCount() {
        return scheduleList == null ? 0 : scheduleList.size();
    }

    @Override
    public Object getItem(int position) {
        return scheduleList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = View.inflate(mContext, R.layout.fragment_course_manage_item,
                    null);
            holder.leftColor = convertView.findViewById(R.id.v_left_color);
            holder.date = (TextView) convertView.findViewById(R.id.tv_course_manage_date);
            holder.startTime = (TextView) convertView.findViewById(R.id
                    .tv_course_manage_start_time);
            holder.endTime = (TextView) convertView.findViewById(R.id
                    .tv_course_manage_end_time);
            holder.content = (TextView) convertView.findViewById(R.id.tv_content);
            holder.statusBtn = (TextView) convertView.findViewById(R.id.tv_satus_btn);
            holder.starImg = (LinearLayout) convertView.findViewById(R.id.ll_star);

            holder.partake = (LinearLayout) convertView.findViewById(R.id
                    .ll_partake_course_manage);
            holder.num = (TextView) convertView.findViewById(R.id.tv_num_course_manage);
            holder.sum = (TextView) convertView.findViewById(R.id.tv_sum_course_manage);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        //开始日期
        String startDate = WLXDateUtil.getDateToString(scheduleList.get(position)
                .getOpening_date());
        //结束日期
        String endDate = WLXDateUtil.getDateToString(scheduleList.get(position)
                .getClosing_date());
        String mouthDay = startDate.substring(startDate.lastIndexOf("年") + 1, startDate
                .lastIndexOf(" "));
        String startTime = startDate.substring(startDate.lastIndexOf(" ") + 1, startDate
                .lastIndexOf(":"));
        holder.date.setText(mouthDay);
        holder.startTime.setText(startTime);
        holder.endTime.setText("-" + endDate.substring(endDate.lastIndexOf(" ") + 1,
                endDate.lastIndexOf(":")));
        String prepareContent = scheduleList.get(position).getPrepare_content();
        WLXLogUtil.printE("getView课程内容: "+prepareContent);
        if (!TextUtils.isEmpty(prepareContent)) {
            holder.content.setText(prepareContent);
        } else {
            holder.content.setText("暂无内容");
        }
        long startTimestamp = scheduleList.get(position).getOpening_date();
        long endTimestamp = scheduleList.get(position).getClosing_date();

        //判断当前时间距离上课上课时间半小时内并且不大于下课时间之间
//            if (currentTimestamp >= startTimestamp && currentTimestamp <= endTimestamp) {
        if (startTimestamp - currentTimestamp < 1800 && currentTimestamp <= endTimestamp) {
//                holder.partake.setVisibility(View.GONE);
            //item左边设置为黄色
            holder.leftColor.setBackgroundResource(R.drawable
                    .shape_course_manage_left_yellow_item);
            ViewGroup.LayoutParams layoutParams = holder.leftColor.getLayoutParams();
            layoutParams.width = ConvertUtils.dp2px(mContext, 20);
            holder.leftColor.setLayoutParams(layoutParams);
            //已上课,判断是否点名,1为已点名,0为未点名
            if (scheduleList.get(position).getIs_study() == 0) {
                holder.statusBtn.setVisibility(View.VISIBLE);
                holder.statusBtn.setText("点名");
                holder.statusBtn.setTextSize(15);
                holder.statusBtn.setBackgroundResource(R.drawable.yellowcircle);
                holder.starImg.setVisibility(View.VISIBLE);
                //隐藏出勤图标
                holder.partake.setVisibility(View.GONE);
//                String prepareContent = scheduleList.get(position).getPrepare_content();
//                WLXLogUtil.printE("getView课程内容: "+prepareContent);
//                if (!TextUtils.isEmpty(prepareContent)) {
//                    holder.content.setText(prepareContent);
//                } else {
//                    holder.content.setText("暂无内容");
//                }
            } else {
                int studyNum = 0;
                holder.statusBtn.setVisibility(View.GONE);
                holder.partake.setVisibility(View.VISIBLE);
                ArrayList<String> studyCodes = new ArrayList();
                countStudyNum(position, holder, studyNum, studyCodes);
            }
        } else if (currentTimestamp < startTimestamp) {
            //未上课,item左边设置为蓝色
            holder.leftColor.setBackgroundResource(R.drawable
                    .shape_course_manage_left__blue_item);
            holder.partake.setVisibility(View.GONE);
            holder.starImg.setVisibility(View.GONE);
            holder.statusBtn.setVisibility(View.VISIBLE);
            holder.statusBtn.setBackgroundResource(R.drawable.graycircle);
            holder.statusBtn.setText("未上课");
            holder.statusBtn.setTextSize(12);
//            holder.content.setText("暂无内容");
            ViewGroup.LayoutParams layoutParams = holder.leftColor.getLayoutParams();
            layoutParams.width = ConvertUtils.dp2px(mContext, 10);
            holder.leftColor.setLayoutParams(layoutParams);
        } else {
            //已结束课程,item左边设置为灰色
//                holder.partake.setVisibility(View.GONE);
            holder.starImg.setVisibility(View.VISIBLE);
            holder.leftColor.setBackgroundResource(R.drawable
                    .shape_course_manage_left_gray_item);
            ViewGroup.LayoutParams layoutParams = holder.leftColor.getLayoutParams();
            layoutParams.width = ConvertUtils.dp2px(mContext, 10);
            holder.leftColor.setLayoutParams(layoutParams);
            if (scheduleList.get(position).getIs_study() == 0) {
                holder.partake.setVisibility(View.GONE);
                holder.statusBtn.setVisibility(View.VISIBLE);
                holder.statusBtn.setText("点名");
                holder.statusBtn.setTextSize(15);
                holder.statusBtn.setBackgroundResource(R.drawable.yellowcircle);
//                String prepareContent = scheduleList.get(position).getPrepare_content();
//                if (!TextUtils.isEmpty(prepareContent)) {
//                    holder.content.setText(prepareContent);
//                } else {
//                    holder.content.setText("暂无内容");
//                }
            } else {
                int studyNum = 0;
                holder.statusBtn.setVisibility(View.GONE);
                holder.partake.setVisibility(View.VISIBLE);
                ArrayList<String> studyCodes = new ArrayList();
                countStudyNum(position, holder, studyNum, studyCodes);
            }
        }
        if (holder.statusBtn.getText().toString().trim().equals("点名")) {
            holder.statusBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String schedule_id = scheduleList.get(position).getSchedule_id();
                    Integer isAddition = (scheduleList.get(position)
                            .getIs_addition());
                    String studentIds = scheduleList.get(position).getAddition_student_ids();
                    Intent intent=new Intent(mContext, WLXCourseRollCallActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString(WLXTeacherConstant.GRADE_ID, grade_id);
                    bundle.putString(WLXTeacherConstant.SCHEDULE_ID, schedule_id);
                    bundle.putInt(WLXTeacherConstant.IS_ADDITION, isAddition);
                    bundle.putString(WLXTeacherConstant.STUDENT_IDS, studentIds);
                    intent.putExtras(bundle);
                    mContext.startActivity(intent);
                }
            });
        }
        return convertView;
    }

    /**
     * 统计学习人数
     * @param position
     * @param holder
     * @param studyNum
     * @param studyCodes
     */
    private void countStudyNum(int position, ViewHolder holder, int studyNum, ArrayList
            <String> studyCodes) {
        String addition_student_ids = scheduleList.get(position)
                .getAddition_student_ids();
        Integer is_addition = scheduleList.get(position).getIs_addition();
        if (is_addition == 1 && !TextUtils.isEmpty(addition_student_ids)) {
            // TODO: 16/9/29 分割addition_student_ids

        } else {
            List<wlx_student_order_detail> wlxStudentOrderDetails = WLXGreenDaoUtil
                    .getStudentOrderDetailDao().queryBuilder().where
                            (wlx_student_order_detailDao.Properties.Grade_id.eq
                                    (grade_id)).list();
            WLXLogUtil.printE("``````````wlxStudentOrderDetails:" + wlxStudentOrderDetails
                    .size());

            String schedule_id = scheduleList.get(0).getSchedule_id();
            int i = 1;
            for (wlx_student_order_detail orderDetail :
                    wlxStudentOrderDetails) {
                //根据grade_id,schedule_id,student_id查询wlx_student_study表
                List<wlx_student_study> wlxStudentStudies = WLXGreenDaoUtil
                        .getStudentStudyDao()
                        .queryBuilder().where
                                (wlx_student_studyDao.Properties.Grade_id.eq(orderDetail
                                                .getGrade_id()),/*
                        wlx_student_studyDao.Properties.Schedule_id.eq
                                (schedule_id),*/
                                        wlx_student_studyDao.Properties.Student_id.eq
                                                (orderDetail
                                                        .getStudent_id())).list();
                if (wlxStudentStudies.size() == 0) {
                    continue;
                }
                String studyStatusCode = wlxStudentStudies.get(position)
                        .getStudy_status_code();
                WLXLogUtil.printE("``````````studyStatusCode:" + i + "-----" + studyStatusCode);
                i++;
                studyCodes.add(studyStatusCode);
            }
            WLXLogUtil.printE("``````````studyCodes:" + studyCodes.size());
            for (String studyCode : studyCodes) {
                if (studyCode.equals("study")) {
                    studyNum++;
                }
            }
                holder.num.setText(studyNum + "");
                holder.sum.setText(studyCodes.size() + "");
            //判断全勤
            if (studyNum==studyCodes.size()) {
                holder.partake.setVisibility(View.GONE);
                holder.statusBtn.setVisibility(View.VISIBLE);
                holder.statusBtn.setText("全勤");
            }
        }
    }

    private static class ViewHolder {
        TextView date;
        TextView startTime;
        TextView endTime;
        TextView content;
        TextView statusBtn;
        LinearLayout starImg;
        LinearLayout partake; //出勤
        TextView num;
        TextView sum;
        View leftColor;
    }
}